package ui;

import model.User;
import model.Order;
import model.RedWine;
import model.Order.OrderStatus;
import service.UserService;
import service.OrderService;
import service.RedWineService;
import factory.ServiceFactory;
import util.OrderCodeUtil;
import util.InputValidator;
import util.StringUtil;

import java.util.List;
import java.util.Scanner;

public class AdminUI extends UI { //管理员界面 完成人：姜凯严、张滨铄 7/6
    private User currentAdmin; 
    private UserService userService = ServiceFactory.getUserService();
    private OrderService orderService = ServiceFactory.getOrderService();
    private RedWineService redWineService = ServiceFactory.getRedWineService();

    public AdminUI(User admin) {
        this.currentAdmin = admin;
    }

    @Override
    public void show() { //覆写父类show()方法
        System.out.println("红酒销售管理系统 - 管理员权限（欢迎您，" + currentAdmin.getUsername() + "）");
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("1. 用户信息管理");
            System.out.println("2. 订单信息管理");
            System.out.println("3. 红酒信息管理");
            System.out.println("4. 订单处理"); 
            System.out.println("0. 退出");
            System.out.print("请选择功能: ");
            String choice = scanner.nextLine();
            if ("1".equals(choice)) {
                userManageMenu(scanner);
            } else if ("2".equals(choice)) {
                orderManageMenu(scanner);
            } else if ("3".equals(choice)) {
                redWineManageMenu(scanner);
            } else if ("4".equals(choice)) {
                orderProcessMenu(scanner); 
            } else if ("0".equals(choice)) {
                break;
            }
        }
    }

    private void orderProcessMenu(Scanner scanner) {
        while (true) {
            System.out.println("---- 订单处理 ----");
            System.out.println("1. 查询所有订单");
            System.out.println("2. 筛选订单");
            System.out.println("3. 进行订单处理");
            System.out.println("0. 返回上级菜单");
            System.out.print("请选择: ");
            String op = scanner.nextLine();
            if ("1".equals(op)) {
                listOrders();
            } else if ("2".equals(op)) {
                filterOrders(scanner);
            } else if ("3".equals(op)) {
                processOrderByCode(scanner);
            } else if ("0".equals(op)) {
                break;
            }
        }
    }

    private void userManageMenu(Scanner scanner) {
        while (true) {
            System.out.println("---- 用户信息管理 ----");
            System.out.println("1. 查询所有用户");
            System.out.println("2. 添加用户");
            System.out.println("3. 修改用户");
            System.out.println("4. 删除用户");
            System.out.println("5. 查找特定用户");
            System.out.println("0. 返回上级菜单");
            System.out.print("请选择: ");
            String op = scanner.nextLine();
            if ("1".equals(op)) {
                listUsers(); 
            } else if ("2".equals(op)) {
                addUser(scanner); 
            } else if ("3".equals(op)) {
                updateUser(scanner); 
            } else if ("4".equals(op)) {
                deleteUser(scanner); 
            } else if ("5".equals(op)) {
                findUser(scanner); 
            } else if ("0".equals(op)) {
                break;
            }
        }
    }

    // 通用用户列表打印方法
    private void printUserList(List<User> users) {
        if (users == null || users.isEmpty()) {
            System.out.println("未找到符合条件的用户！");
            return;
        }
        System.out.println("+--------+----------------+----------+----------------+------------------------+");
        System.out.println("| 用户ID |     用户名     |   余额   |      电话      |         地址           |");
        System.out.println("+--------+----------------+----------+----------------+------------------------+");
        for (User u : users) {
            String username = u.getUsername() != null ? u.getUsername() : "";
            String phone = u.getPhone() != null ? u.getPhone() : "";
            String address = u.getAddress() != null ? u.getAddress() : "";
            
            // 使用显示宽度处理，确保表格对齐
            String displayUsername = StringUtil.truncateByDisplayWidth(username, 14);
            String displayPhone = StringUtil.truncateByDisplayWidth(phone, 14);
            String displayAddress = StringUtil.truncateByDisplayWidth(address, 22);
            
            // 填充到固定显示宽度
            displayUsername = StringUtil.padToDisplayWidth(displayUsername, 14);
            displayPhone = StringUtil.padToDisplayWidth(displayPhone, 14);
            displayAddress = StringUtil.padToDisplayWidth(displayAddress, 22);
            
            System.out.printf("| %-6d | %s | %8.2f | %s | %s |%n", 
                u.getUserId(), displayUsername, u.getBalance(), displayPhone, displayAddress);
            
            // 如果有内容被截断，在下一行显示完整信息
            boolean hasOverflow = false;
            if (StringUtil.getDisplayWidth(username) > 14) {
                System.out.printf("|        | 完整用户名: %-60s |%n", username);
                hasOverflow = true;
            }
            if (StringUtil.getDisplayWidth(phone) > 14) {
                System.out.printf("|        | 完整电话: %-62s |%n", phone);
                hasOverflow = true;
            }
            if (StringUtil.getDisplayWidth(address) > 22) {
                System.out.printf("|        | 完整地址: %-62s |%n", address);
                hasOverflow = true;
            }
            if (hasOverflow) {
                System.out.println("+--------+----------------+----------+----------------+------------------------+");
            }
        }
        System.out.println("+--------+----------------+----------+----------------+------------------------+");
    }

    private void listUsers() { // 查询所有用户
        List<User> users = userService.findAll();
        printUserList(users);
    }

    private void addUser(Scanner scanner) { // 添加用户
        System.out.println("=== 添加用户 ===");
        
        // 使用InputValidator工具类进行用户名校验
        String username = InputValidator.getValidNonEmptyString(scanner, "用户名: ", "用户名");
        if (username == null) return; // 校验失败
        
        // 检查用户名是否已存在
        List<User> existUsers = userService.findByUsername(username);
        if (existUsers != null && !existUsers.isEmpty()) {
            System.out.println("用户名已存在！");
            return;
        }
        
        // 使用InputValidator工具类进行密码校验
        String password = InputValidator.getValidNonEmptyString(scanner, "密码: ", "密码");
        if (password == null) return; // 校验失败
        
        System.out.print("地址（可留空）: ");
        String address = scanner.nextLine().trim();
        
        System.out.print("电话（可留空）: ");
        String phone = scanner.nextLine().trim();
        
        // 使用InputValidator工具类进行余额校验（可留空）
        double balance = InputValidator.getValidNonNegativeDoubleOptional(scanner, 
            "余额（可留空，默认为0）: ", "余额", 0.0);
        if (balance == -1) return; // 校验失败
        
        // 根据输入情况自动选择添加方式
        if (address.isEmpty() && phone.isEmpty() && balance == 0.0) {
            // 快速添加：只有用户名和密码
            if (userService.addUser(username, password)) {
                System.out.println("添加成功！（使用快速添加模式：余额默认为0，地址和电话为空）");
            } else {
                System.out.println("添加失败！");
            }
        } else {
            // 完整添加：包含其他信息
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setAddress(address.isEmpty() ? "" : address);
            user.setPhone(phone.isEmpty() ? "" : phone);
            user.setBalance(balance);
            user.setPermissionLevel(User.PermissionLevel.normal); // 默认普通用户
            
            if (userService.addUser(user)) {
                System.out.println("添加成功！（使用完整添加模式）");
            } else {
                System.out.println("添加失败！");
            }
        }
    }

    private void updateUser(Scanner scanner) { // 修改用户
        // 使用InputValidator工具类进行用户ID校验
        int userId = InputValidator.getValidPositiveInt(scanner, "请输入要修改的用户ID: ", "用户ID");
        
        User user = userService.findById(userId);
        if (user == null) {
            System.out.println("用户不存在！");
            return;
        }
        System.out.print("新用户名(" + user.getUsername() + "): ");
        String username = scanner.nextLine();
        if (!username.isEmpty()) user.setUsername(username);
        System.out.print("新密码(留空不变): ");
        String password = scanner.nextLine();
        if (!password.isEmpty()) user.setPassword(password);
        System.out.print("新地址(" + user.getAddress() + "): ");
        String address = scanner.nextLine();
        if (!address.isEmpty()) user.setAddress(address);
        System.out.print("新电话(" + user.getPhone() + "): ");
        String phone = scanner.nextLine();
        if (!phone.isEmpty()) user.setPhone(phone);
        
        // 使用InputValidator工具类进行新余额校验（可留空）
        double newBalance = InputValidator.getValidNonNegativeDoubleOptional(scanner, 
            "新余额(" + user.getBalance() + "): ", "余额", user.getBalance());
        if (newBalance == -1) return; // 校验失败
        user.setBalance(newBalance);
        
        if (userService.updateUser(user)) {
            System.out.println("修改成功！");
        } else {
            System.out.println("修改失败！");
        }
    }

    private void deleteUser(Scanner scanner) { // 删除用户
        // 使用InputValidator工具类进行用户ID校验
        int userId = InputValidator.getValidPositiveInt(scanner, "请输入要删除的用户ID: ", "用户ID");
        
        if (userService.deleteUser(userId)) {
            System.out.println("删除成功！");
        } else {
            System.out.println("删除失败！");
        }
    }

    private void findUser(Scanner scanner) { // 查找特定用户
        System.out.print("请输入用户名(可留空): ");
        String username = scanner.nextLine().trim();
        System.out.print("请输入电话(可留空): ");
        String phone = scanner.nextLine().trim();
        List<User> users;
        if (!username.isEmpty() && !phone.isEmpty()) {
            users = userService.findByUsernameAndPhone(username, phone);
        } else if (!username.isEmpty()) {
            users = userService.findByUsername(username);
        } else if (!phone.isEmpty()) {
            users = userService.findByPhone(phone);
        } else {
            System.out.println("用户名和电话不能同时为空！");
            return;
        }
        if (users.isEmpty()) {
            System.out.println("未找到用户！");
        } else {
            printUserList(users);
        }
    }

    private void orderManageMenu(Scanner scanner) {
        while (true) {
            System.out.println("---- 订单信息管理 ----");
            System.out.println("1. 查询所有订单");
            System.out.println("2. 添加订单");
            System.out.println("3. 修改订单");
            System.out.println("4. 删除订单");
            System.out.println("5. 筛选订单");
            System.out.println("0. 返回上级菜单");
            System.out.print("请选择: ");
            String op = scanner.nextLine();
            if ("1".equals(op)) {
                listOrders();
            } else if ("2".equals(op)) {
                addOrder(scanner);
            } else if ("3".equals(op)) {
                updateOrder(scanner);
            } else if ("4".equals(op)) {
                deleteOrderMenu(scanner); 
            } else if ("5".equals(op)) {
                filterOrders(scanner);
            } else if ("0".equals(op)) {
                break;
            }
        }
    }

    private void deleteOrderMenu(Scanner scanner) {
        System.out.println("---- 删除订单 ----");
        System.out.println("1. 按订单ID删除");
        System.out.println("2. 按标识码删除");
        System.out.print("请选择: ");
        String op = scanner.nextLine();
        if ("1".equals(op)) {
            deleteOrderByOrderId(scanner);
        } else if ("2".equals(op)) {
            deleteOrderByCode(scanner);
        }
    }

    private void deleteOrderByOrderId(Scanner scanner) {
        // 使用InputValidator工具类进行订单ID校验
        int orderId = InputValidator.getValidPositiveInt(scanner, "请输入要删除的订单ID: ", "订单ID");
        
        List<Order> orders = orderService.findAll();
        boolean deleted = false;
        for (Order o : orders) {
            if (o.getOrderId() == orderId) {
                // 获取红酒信息
                RedWine redWine = redWineService.findById(o.getRedWineId());
                if (redWine != null) {
                    // 删除订单
                    if (orderService.deleteOrder(o.getOrderId())) {
                        // 恢复红酒库存
                        int newStock = redWine.getStock() + o.getQuantity();
                        if (redWineService.updateRedWine(o.getRedWineId(), newStock)) {
                            System.out.println("删除成功！红酒库存已恢复，当前库存: " + newStock);
                        } else {
                            System.out.println("订单删除成功，但库存恢复失败！");
                        }
                        deleted = true;
                    }
                } else {
                    System.out.println("红酒信息不存在，无法恢复库存！");
                }
                break;
            }
        }
        if (!deleted) {
            System.out.println("删除失败或未找到该订单ID！");
        }
    }

    private void deleteOrderByCode(Scanner scanner) {
        // 使用InputValidator工具类进行标识码校验
        int code = InputValidator.getValidPositiveInt(scanner, "请输入要删除的标识码: ", "标识码");
        
        List<Order> orders = orderService.findAll();
        List<Order> ordersToDelete = new java.util.ArrayList<>();
        
        // 先收集所有匹配标识码的订单
        for (Order o : orders) {
            if (o.getCode() == code) {
                ordersToDelete.add(o);
            }
        }
        
        if (ordersToDelete.isEmpty()) {
            System.out.println("未找到该标识码的订单！");
            return;
        }
        
        System.out.println("找到 " + ordersToDelete.size() + " 个匹配的订单：");
        super.printOrderList(ordersToDelete); // 显示要删除的订单
        
        System.out.print("确认删除以上所有订单吗？(y/n): ");
        String confirmation = scanner.nextLine().trim();
        if (!"y".equalsIgnoreCase(confirmation)) {
            System.out.println("取消删除操作。");
            return;
        }
        
        int deletedCount = 0;
        int stockRestoreFailures = 0;
        
        // 删除所有匹配的订单并恢复库存
        for (Order o : ordersToDelete) {
            // 获取红酒信息
            RedWine redWine = redWineService.findById(o.getRedWineId());
            if (redWine != null) {
                // 删除订单
                if (orderService.deleteOrder(o.getOrderId())) {
                    // 恢复红酒库存
                    int newStock = redWine.getStock() + o.getQuantity();
                    if (redWineService.updateRedWine(o.getRedWineId(), newStock)) {
                        System.out.println("订单ID " + o.getOrderId() + " 删除成功！红酒库存已恢复，当前库存: " + newStock);
                    } else {
                        System.out.println("订单ID " + o.getOrderId() + " 删除成功，但库存恢复失败！");
                        stockRestoreFailures++;
                    }
                    deletedCount++;
                } else {
                    System.out.println("订单ID " + o.getOrderId() + " 删除失败！");
                }
            } else {
                System.out.println("订单ID " + o.getOrderId() + " 对应的红酒信息不存在，无法恢复库存！");
                // 仍然尝试删除订单
                if (orderService.deleteOrder(o.getOrderId())) {
                    deletedCount++;
                    stockRestoreFailures++;
                }
            }
        }
        
        // 输出删除结果摘要
        System.out.println("=== 删除操作完成 ===");
        System.out.println("成功删除订单数: " + deletedCount + "/" + ordersToDelete.size());
        if (stockRestoreFailures > 0) {
            System.out.println("库存恢复失败订单数: " + stockRestoreFailures);
        }
        if (deletedCount == ordersToDelete.size() && stockRestoreFailures == 0) {
            System.out.println("所有订单删除成功，库存全部恢复！");
        }
    }

    private void filterOrders(Scanner scanner) {
        System.out.println("---- 订单筛选 ----");
        System.out.println("1. 按订单ID筛选");
        System.out.println("2. 按用户ID筛选");
        System.out.println("3. 按红酒ID筛选");
        System.out.println("4. 按标识码筛选");
        System.out.print("请选择筛选方式: ");
        String op = scanner.nextLine();
        List<Order> orders = orderService.findAll();
        if ("1".equals(op)) {
            // 使用InputValidator工具类进行订单ID校验
            int orderId = InputValidator.getValidPositiveInt(scanner, "请输入订单ID: ", "订单ID");
            orders = filterOrderList(orders, orderId, null, null, null, scanner);
            super.printOrderList(orders); // 调用父类方法
        } else if ("2".equals(op)) {
            // 使用InputValidator工具类进行用户ID校验（可留空）
            int userId = InputValidator.getValidPositiveIntOptional(scanner, 
                "请输入用户ID(可留空): ", "用户ID", 0);
            if (userId == -1) return; // 校验失败
            Integer userIdParam = (userId == 0) ? null : userId;
            orders = filterOrderList(orders, null, userIdParam, null, null, scanner);
            super.printOrderList(orders); // 调用父类方法
        } else if ("3".equals(op)) {
            // 使用InputValidator工具类进行红酒ID校验（可留空）
            int redWineId = InputValidator.getValidPositiveIntOptional(scanner, 
                "请输入红酒ID(可留空): ", "红酒ID", 0);
            if (redWineId == -1) return; // 校验失败
            Integer redWineIdParam = (redWineId == 0) ? null : redWineId;
            orders = filterOrderList(orders, null, null, redWineIdParam, null, scanner);
            super.printOrderList(orders); // 调用父类方法
        } else if ("4".equals(op)) {
            // 使用InputValidator工具类进行标识码校验
            int code = InputValidator.getValidPositiveInt(scanner, "请输入标识码: ", "标识码");
            orders = filterOrderList(orders, null, null, null, code, scanner);
            super.printOrderList(orders); // 调用父类方法
        }
    }

    /**
     * 对订单列表进行二次筛选：订单状态、是否线上
     */
    private List<Order> filterOrderList(List<Order> orders, Integer orderId, Integer userId, Integer redWineId, Integer code, Scanner scanner) {
        // 先按ID筛选
        List<Order> filtered = new java.util.ArrayList<>();
        for (Order o : orders) {
            if (orderId != null && o.getOrderId() != orderId) continue;
            if (userId != null && o.getUserId() != userId) continue;
            if (redWineId != null && o.getRedWineId() != redWineId) continue;
            if (code != null && o.getCode() != code) continue;
            filtered.add(o);
        }
        // 订单状态筛选
        System.out.print("请输入订单状态(未付款/已付款/待收货/已完成，可留空): ");
        String statusStr = scanner.nextLine().trim();
        if (!statusStr.isEmpty()) {
            try {
                OrderStatus status = OrderStatus.valueOf(statusStr);
                filtered.removeIf(o -> o.getStatus() != status);
            } catch (Exception e) {
                System.out.println("状态输入有误，忽略状态筛选。");
            }
        }
        // 是否线上筛选
        System.out.print("是否线上订单(1=线上, 0=线下, 留空为全部): ");
        String onlineStr = scanner.nextLine().trim();
        if ("1".equals(onlineStr)) {
            filtered.removeIf(o -> !o.isOnline());
        } else if ("0".equals(onlineStr)) {
            filtered.removeIf(Order::isOnline);
        }
        return filtered;
    }

    // 调用父类的通用订单打印方法
    private void listOrders() { // 查询所有订单
        List<Order> orders = orderService.findAll();
        super.printOrderList(orders); // 调用父类方法
    }

    private void addOrder(Scanner scanner) { // 添加订单
        // 使用InputValidator工具类进行用户ID校验
        int userId = InputValidator.getValidPositiveInt(scanner, "用户ID: ", "用户ID");
        
        // 自动生成唯一8位标识码
        List<Order> allOrders = orderService.findAll();
        int code = OrderCodeUtil.generateUniqueOrderCode(allOrders);
        System.out.println("本次订单标识码为: " + code);
        
        // 使用InputValidator工具类进行订单状态校验
        OrderStatus status = InputValidator.getValidOrderStatus(scanner, "状态(未付款/已付款/待收货/已完成): ");
        
        // 使用InputValidator工具类进行是否线上订单校验
        boolean online = InputValidator.getValidBoolean(scanner, "是否线上订单(1=线上, 0=线下): ", "是否线上订单");
        
        while (true) {
            // 使用InputValidator工具类进行红酒ID校验
            int redWineId = InputValidator.getValidNonNegativeInt(scanner, "红酒ID(输入0结束): ", "红酒ID");
            
            if (redWineId == 0) break;
            
            // 检查红酒是否存在
            RedWine redWine = redWineService.findById(redWineId);
            if (redWine == null) {
                System.out.println("红酒不存在，请重新输入！");
                continue;
            }
            
            // 输入数量并检查库存
            int quantity;
            while (true) {
                quantity = InputValidator.getValidPositiveInt(scanner, "数量: ", "数量");
                
                // 检查库存是否充足
                if (redWine.getStock() < quantity) {
                    System.out.println("库存不足！当前库存: " + redWine.getStock() + "，请重新输入数量:");
                    continue;
                }
                break;
            }
            
            // 创建订单
            Order order = new Order(0, userId, redWineId, quantity, status, online, code);
            if (orderService.addOrder(order)) {
                // 减少红酒库存
                int newStock = redWine.getStock() - quantity;
                if (redWineService.updateRedWine(redWineId, newStock)) {
                    System.out.println("添加成功！红酒库存已更新，剩余库存: " + newStock);
                } else {
                    System.out.println("订单添加成功，但库存更新失败！");
                }
            } else {
                System.out.println("添加失败！");
            }
        }
    }

    private void updateOrder(Scanner scanner) { // 修改订单
        // 使用InputValidator工具类进行订单ID校验
        int orderId = InputValidator.getValidPositiveInt(scanner, "请输入要修改的订单ID: ", "订单ID");
        
        // 查找订单
        List<Order> orders = orderService.findAll();
        Order order = null;
        for (Order o : orders) {
            if (o.getOrderId() == orderId) {
                order = o;
                break;
            }
        }
        if (order == null) {
            System.out.println("订单不存在！");
            return;
        }
        
        // 使用InputValidator工具类进行新用户ID校验（可留空）
        int newUserId = InputValidator.getValidPositiveIntOptional(scanner, 
            "新用户ID(" + order.getUserId() + "): ", "用户ID", order.getUserId());
        if (newUserId == -1) return; // 校验失败
        order.setUserId(newUserId);
        
        // 使用InputValidator工具类进行新红酒ID校验（可留空）
        int newRedWineId = InputValidator.getValidPositiveIntOptional(scanner, 
            "新红酒ID(" + order.getRedWineId() + "): ", "红酒ID", order.getRedWineId());
        if (newRedWineId == -1) return; // 校验失败
        order.setRedWineId(newRedWineId);
        
        // 使用InputValidator工具类进行新数量校验（可留空）
        int newQuantity = InputValidator.getValidPositiveIntOptional(scanner, 
            "新数量(" + order.getQuantity() + "): ", "数量", order.getQuantity());
        if (newQuantity == -1) return; // 校验失败
        order.setQuantity(newQuantity);
        
        // 使用InputValidator工具类进行新状态校验（可留空）
        OrderStatus newStatus = InputValidator.getValidOrderStatusOptional(scanner, 
            "新状态(" + order.getStatus().name() + "): ", order.getStatus());
        if (newStatus == null) return; // 校验失败
        order.setStatus(newStatus);
        
        // 使用InputValidator工具类进行是否线上订单校验（可留空）
        Boolean newOnline = InputValidator.getValidBooleanOptional(scanner, 
            "是否线上订单(" + (order.isOnline() ? "1" : "0") + "): ", "是否线上订单", order.isOnline());
        if (newOnline == null) return; // 校验失败
        order.setOnline(newOnline);
        
        // 使用InputValidator工具类进行新标识码校验（可留空）
        int newCode = InputValidator.getValidPositiveIntOptional(scanner, 
            "新标识码(" + order.getCode() + "): ", "标识码", order.getCode());
        if (newCode == -1) return; // 校验失败
        order.setCode(newCode);
        
        if (orderService.updateOrder(order)) {
            System.out.println("修改成功！");
        } else {
            System.out.println("修改失败！");
        }
    }

    private void redWineManageMenu(Scanner scanner) {
        while (true) {
            System.out.println("---- 红酒信息管理 ----");
            System.out.println("1. 查询所有红酒");
            System.out.println("2. 添加红酒");
            System.out.println("3. 修改红酒");
            System.out.println("4. 删除红酒");
            System.out.println("5. 筛选红酒"); // 新增
            System.out.println("0. 返回上级菜单");
            System.out.print("请选择: ");
            String op = scanner.nextLine();
            if ("1".equals(op)) {
                listRedWines(); // 查询所有红酒
            } else if ("2".equals(op)) {
                addRedWine(scanner); // 添加红酒
            } else if ("3".equals(op)) {
                updateRedWine(scanner); // 修改红酒
            } else if ("4".equals(op)) {
                deleteRedWine(scanner); // 删除红酒
            } else if ("5".equals(op)) {
                super.filterRedWine(scanner); // 调用父类方法
            } else if ("0".equals(op)) {
                break;
            }
        }
    }

    private void addRedWine(Scanner scanner) { // 添加红酒
        System.out.println("=== 添加红酒 ===");
        
        // 使用InputValidator工具类进行酒名校验
        String name = InputValidator.getValidNonEmptyString(scanner, "酒名: ", "酒名");
        if (name == null) return; // 校验失败
        
        // 使用InputValidator工具类进行库存校验（可留空）
        int stock = InputValidator.getValidNonNegativeIntOptional(scanner, 
            "库存（可只输入酒名，留空默认为0）: ", "库存", 0);
        if (stock == -1) return; // 校验失败
        
        // 使用InputValidator工具类进行单价校验（可留空）
        double price = InputValidator.getValidNonNegativeDoubleOptional(scanner, 
            "单价（可只输入酒名，留空默认为0）: ", "单价", 0.0);
        if (price == -1) return; // 校验失败
        
        System.out.print("国家（可留空）: ");
        String country = scanner.nextLine().trim();
        
        System.out.print("城市（可留空）: ");
        String city = scanner.nextLine().trim();
        
        System.out.print("县（可留空）: ");
        String county = scanner.nextLine().trim();
        
        // 根据输入情况自动选择添加方式
        if (stock == 0 && price == 0.0 && 
            country.isEmpty() && city.isEmpty() && county.isEmpty()) {
            // 仅酒名模式
            if (redWineService.addRedWine(name)) {
                System.out.println("添加成功！（仅酒名模式：库存和单价默认为0，产地信息为空）");
            } else {
                System.out.println("添加失败！");
            }
        } else if (stock > 0 && price > 0.0 && 
                   country.isEmpty() && city.isEmpty() && county.isEmpty()) {
            // 酒名+库存+单价模式
            if (redWineService.addRedWine(name, stock, price)) {
                System.out.println("添加成功！（基本信息模式：产地信息为空）");
            } else {
                System.out.println("添加失败！");
            }
        } else {
            // 完整信息模式
            RedWine rw = new RedWine();
            rw.setName(name);
            rw.setStock(stock);
            rw.setPrice(price);
            rw.setCountry(country.isEmpty() ? "" : country);
            rw.setCity(city.isEmpty() ? "" : city);
            rw.setCounty(county.isEmpty() ? "" : county);
            
            if (redWineService.addRedWine(rw)) {
                System.out.println("添加成功！（完整信息模式）");
            } else {
                System.out.println("添加失败！");
            }
        }
    }

    private void updateRedWine(Scanner scanner) { // 修改红酒
        // 使用InputValidator工具类进行红酒ID校验
        int redWineId = InputValidator.getValidPositiveInt(scanner, "请输入要修改的红酒ID: ", "红酒ID");
        
        RedWine rw = redWineService.findById(redWineId);
        if (rw == null) {
            System.out.println("红酒不存在！");
            return;
        }
        
        System.out.print("新酒名(" + rw.getName() + "): ");
        String name = scanner.nextLine();
        if (!name.isEmpty()) rw.setName(name);
        
        // 使用InputValidator工具类进行新库存校验（可留空）
        int newStock = InputValidator.getValidNonNegativeIntOptional(scanner, 
            "新库存(" + rw.getStock() + "): ", "库存", rw.getStock());
        if (newStock == -1) return; // 校验失败
        rw.setStock(newStock);
        
        // 使用InputValidator工具类进行新单价校验（可留空）
        double newPrice = InputValidator.getValidNonNegativeDoubleOptional(scanner, 
            "新单价(" + rw.getPrice() + "): ", "单价", rw.getPrice());
        if (newPrice == -1) return; // 校验失败
        rw.setPrice(newPrice);
        
        System.out.print("新国家(" + rw.getCountry() + "): ");
        String country = scanner.nextLine();
        if (!country.isEmpty()) rw.setCountry(country);
        System.out.print("新城市(" + rw.getCity() + "): ");
        String city = scanner.nextLine();
        if (!city.isEmpty()) rw.setCity(city);
        System.out.print("新县(" + rw.getCounty() + "): ");
        String county = scanner.nextLine();
        if (!county.isEmpty()) rw.setCounty(county);
        
        if (redWineService.updateRedWine(rw)) {
            System.out.println("修改成功！");
        } else {
            System.out.println("修改失败！");
        }
    }

    private void deleteRedWine(Scanner scanner) { // 删除红酒
        // 使用InputValidator工具类进行红酒ID校验
        int redWineId = InputValidator.getValidPositiveInt(scanner, "请输入要删除的红酒ID: ", "红酒ID");
        
        if (redWineService.deleteRedWine(redWineId)) {
            System.out.println("删除成功！");
        } else {
            System.out.println("删除失败！");
        }
    }

    private void processOrderByCode(Scanner scanner) {
        // 使用InputValidator工具类进行标识码校验
        int code = InputValidator.getValidPositiveInt(scanner, "请输入要处理的订单标识码: ", "标识码");
        
        List<Order> orders = orderService.findAll();
        List<Order> targetOrders = new java.util.ArrayList<>();
        for (Order o : orders) {
            if (o.getCode() == code) {
                targetOrders.add(o);
            }
        }
        if (targetOrders.isEmpty()) {
            System.out.println("未找到该标识码的订单！");
            return;
        }
        Order sample = targetOrders.get(0);
        OrderStatus status = sample.getStatus();
        boolean online = sample.isOnline();
        int userId = sample.getUserId();

        if (status == OrderStatus.未付款) {
            System.out.print("当前状态为“未付款”，是否更改为“已付款”？(y/n): ");
            String input = scanner.nextLine().trim();
            if ("y".equalsIgnoreCase(input)) {
                for (Order o : targetOrders) o.setStatus(OrderStatus.已付款);
                boolean ok = true;
                for (Order o : targetOrders) ok &= orderService.updateOrder(o);
                System.out.println(ok ? "订单状态已更改为“已付款”！" : "订单状态更改失败！");
            }
        } else if (status == OrderStatus.已付款) {
            if (online) {
                User user = userService.findById(userId);
                String address = (user != null && user.getAddress() != null && !user.getAddress().isEmpty()) ? user.getAddress() : "（无地址信息）";
                System.out.print("当前为线上订单，用户地址为：" + address + "，是否发货并更改为“待收货”？(y/n): ");
                String input = scanner.nextLine().trim();
                if ("y".equalsIgnoreCase(input)) {
                    for (Order o : targetOrders) o.setStatus(OrderStatus.待收货);
                    boolean ok = true;
                    for (Order o : targetOrders) ok &= orderService.updateOrder(o);
                    System.out.println(ok ? "订单状态已更改为“待收货”！" : "订单状态更改失败！");
                }
            } else {
                System.out.print("当前为线下订单，是否更改为“待收货”？(y/n): ");
                String input = scanner.nextLine().trim();
                if ("y".equalsIgnoreCase(input)) {
                    for (Order o : targetOrders) o.setStatus(OrderStatus.待收货);
                    boolean ok = true;
                    for (Order o : targetOrders) ok &= orderService.updateOrder(o);
                    System.out.println(ok ? "订单状态已更改为“待收货”！" : "订单状态更改失败！");
                }
            }
        } else if (status == OrderStatus.待收货) {
            System.out.print("当前状态为“待收货”，是否更改为“已完成”？(y/n): ");
            String input = scanner.nextLine().trim();
            if ("y".equalsIgnoreCase(input)) {
                for (Order o : targetOrders) o.setStatus(OrderStatus.已完成);
                boolean ok = true;
                for (Order o : targetOrders) ok &= orderService.updateOrder(o);
                System.out.println(ok ? "订单状态已更改为“已完成”！" : "订单状态更改失败！");
            }
        } else {
            System.out.println("订单已完成或状态不支持进一步处理。");
        }
    }
}